package com.example.mes_sys.security;

import com.example.mes_sys.po.SysRolePo;
import com.example.mes_sys.po.SysUserPo;
import com.example.mes_sys.po.SysUserRoleRelationPo;
import com.example.mes_sys.repository.*;
import com.example.mes_sys.vo.UserDetailsVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserRepository userRepository;
    @Autowired
    private SysUserRoleRelationRepository userRoleRelationRepository;
    @Autowired
    private SysRoleRepository roleRepository;
    //根据用户名获取用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获取用户
        SysUserPo sysUserPo = userRepository.findByUserName(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));
        return getUserDetails(sysUserPo);
    }
    //根据用户id获取用户信息
    public UserDetails loadUserById(Long userId) {
        //根据用户名获取用户
        SysUserPo sysUserPo = userRepository.findById(userId)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with userId: " + userId));
        return getUserDetails(sysUserPo);
    }
    public UserDetails getUserDetails(SysUserPo sysUserPo) {
        //根据用户获取角色
        List<SysUserRoleRelationPo> sysUserRoleRelations = userRoleRelationRepository.findByUserId(sysUserPo.getId())
                .orElseThrow(() -> new UsernameNotFoundException("Role not found with userName:" + sysUserPo.getUserName()));
        List<Long> roleIdList = sysUserRoleRelations.stream().map(SysUserRoleRelationPo::getRoleId).toList();
        //获取角色列表
        List<SysRolePo> sysRolePoList = roleRepository.findByIdIn(roleIdList);

        UserDetailsVo userDetailsVo = new UserDetailsVo();
        BeanUtils.copyProperties(sysUserPo, userDetailsVo);
        List<GrantedAuthority> authorities = new ArrayList<>(sysRolePoList.size());

        for(SysRolePo sysRolePo : sysRolePoList) {
            String role = sysRolePo.getRoleCode();
            authorities.add(new SimpleGrantedAuthority(role));
        }
        userDetailsVo.setAuthorities(authorities);

        return userDetailsVo;
    }
}